package keensky.loginandupload;

import java.io.IOException;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class MyLogin {
	public static void main(String[] args) {
		//创建一个httpClient的实例
		HttpClient httpClient =new HttpClient();
		
		//登录url的地址
		String loginUrl = "http://git.oschina.net/";
		// 需登陆后访问的 Url
		String dataUrl = "http://git.oschina.net/mizhong";
		PostMethod postMethod=new PostMethod(loginUrl);
//		PostMethod postMethod=new PostMethod(url2);
		//postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3,false));
		//输入用户名和密码
		NameValuePair[] data={new NameValuePair("name", "mizhong127@126.com"),
				new NameValuePair("password", "jingbang")};
		postMethod.setRequestBody(data);
		try {
			//设置cookie
			httpClient.getParams().setCookiePolicy(
					CookiePolicy.BROWSER_COMPATIBILITY);
			int status=httpClient.executeMethod(postMethod);
			System.out.println("status:"+status);

			
			
			Cookie[] cookies = httpClient.getState().getCookies();
			
			StringBuffer tmpcookies = new StringBuffer();
			for (Cookie c : cookies) {
				tmpcookies.append(c.toString() + ";");
				System.out.println("name="+c.getName()+"    value="+c.getValue());
			}
			System.out.println("tmpcookies="+tmpcookies);
			GetMethod getMethod = new GetMethod(dataUrl);
			// 每次访问需授权的cookie
			getMethod.setRequestHeader("cookie", tmpcookies.toString());

			// referer 从哪里来的
			postMethod.setRequestHeader("Referer", "http://git.oschina.net/");
			postMethod.setRequestHeader("User-Agent", "www Spot");
			httpClient.executeMethod(getMethod);
			// 显示出数据
			String text = getMethod.getResponseBodyAsString();
			System.out.println(text);
			
			
			
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//
			postMethod.releaseConnection();
		}
		
	}

}
